package com.smart.manager.product.repository;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.common.entities.option.SelectOption;
import com.smart.manager.product.entities.body.RPigLevel;
import com.smart.manager.product.entities.models.PigLevel;
import com.smart.manager.product.entities.models.query.QPigLevel;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 猪仔配置 - 日龄等级
 *
 * @author leo
 * @date 2023/09/07
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class PigLevelRepository {

    public Page<PigLevel> pageList(RPigLevel.SearchBody search) {
        QPigLevel query = new QPigLevel();
        Opt.ofBlankAble(search.getStage()).ifPresent(x -> query.stage.eq(x));
        Opt.ofBlankAble(search.getKind()).ifPresent(x -> query.kind.eq(x));
        Opt.ofBlankAble(search.getBreed()).ifPresent(x -> query.breed.eq(x));
        Opt.ofBlankAble(search.getAllowKill()).ifPresent(x -> query.allowKill.eq(x));
        query.order().levelNum.asc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<PigLevel>().load(query.findPagedList());
    }

    public void add(RPigLevel.EditBody body) {

        BeanUtil.copyProperties(body, PigLevel.class).save();
    }


    public void update(Long id, RPigLevel.EditBody body) {
        QPigLevel query = new QPigLevel();
        PigLevel record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
    }

    public int delByIds(List<Long> ids) {
        List<PigLevel> list = new QPigLevel().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);

        return DB.deleteAll(list);


    }


    /**
     * 获取数据字典下拉选项
     *
     * @return {@code List<SelectOption>}
     */
    public List<SelectOption> getOptions() {
        QPigLevel place = new QPigLevel();
        return place.findStream()
                .map(x -> new SelectOption()
                        .setLabel(String.valueOf(x.getDay()))
                        .setValue(String.valueOf(x.getLevelNum()))
                        .setDisabled(false))
                .collect(Collectors.toList());
    }

}






